package com.example.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.Statement;

public class DatabaseInitializer {
    public static void main(String[] args) {
        initializeDatabase();
    }
    
    public static void initializeDatabase() {
        try (Connection conn = DBUtil.getConnection()) {
            System.out.println("开始初始化数据库...");
            
            // 读取SQL文件
            String sqlContent = readSQLFile();
            
            // 执行SQL语句
            executeSQL(conn, sqlContent);
            
            System.out.println("数据库初始化完成！");
            
        } catch (Exception e) {
            System.err.println("数据库初始化失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private static String readSQLFile() {
        StringBuilder sql = new StringBuilder();
        try (InputStream is = DatabaseInitializer.class.getClassLoader().getResourceAsStream("complete_database_init.sql");
             BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
            
            String line;
            while ((line = reader.readLine()) != null) {
                // 跳过注释行
                if (line.trim().startsWith("--") || line.trim().isEmpty()) {
                    continue;
                }
                sql.append(line).append("\n");
            }
        } catch (Exception e) {
            System.err.println("读取SQL文件失败: " + e.getMessage());
        }
        return sql.toString();
    }
    
    private static void executeSQL(Connection conn, String sqlContent) throws Exception {
        // 分割SQL语句
        String[] statements = sqlContent.split(";");
        
        try (Statement stmt = conn.createStatement()) {
            for (String statement : statements) {
                String trimmed = statement.trim();
                if (!trimmed.isEmpty()) {
                    try {
                        stmt.execute(trimmed);
                        System.out.println("执行SQL: " + trimmed.substring(0, Math.min(50, trimmed.length())) + "...");
                    } catch (Exception e) {
                        System.err.println("执行SQL失败: " + trimmed);
                        System.err.println("错误: " + e.getMessage());
                    }
                }
            }
        }
    }
} 